package com.topisv.tms.web.focus;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.service.BackupTaskOrdenoService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiOrderService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.web.CancelController;

import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "/focusCancel")
public class FocusCancelController {
	private static final Logger log = LoggerFactory.getLogger(CancelController.class);
	

	@Autowired
	private BackupTaskOrdenoService backupTaskOrdenoService;

	@Autowired
	private CustomersService customersService;
	@Autowired
	private EdiOrderService ediOrderService;

	@RequestMapping(value = "init")
	public String init(Model model) {
		ShiroUser user=getShiroUser();
		List<Customers> customers=customersService.loadCustomerByAuthority(user);
		model.addAttribute("customers", customers);
		return "work/gather/cancelLists";

	}

	@RequestMapping(value = "ajaxCancelOrdeno")
	public void ajaxCancelOrdeno(@RequestParam(value = "id",required=false) Long id,
			@RequestParam(value = "customerCode",required=false) String customerCode,
			@RequestParam(value = "ordeno",required=false) String ordeno,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		EdiOrder e=null;
		ShiroUser user =getShiroUser();
		try {
			json = new JSONObject();
			out = response.getWriter();
			if(id==null){
				log.info("取消的订单订单号为:"+ordeno);
				log.info("取消的订单商家编码为:"+customerCode);
				e=ediOrderService.getEdiOrder(customerCode, ordeno);
				if(e==null){
					json.put("status", "-1");
					json.put("content", "该订单不存在");
					out.print(json.toString());
					return;
				}
			}else{
				log.info("取消的订单ID为:"+id);
				e=ediOrderService.findOne(id);
				if(e==null){
					json.put("status", "-1");
					json.put("content", "该订单不存在");
					out.print(json.toString());
					return;
				}
			}
			backupTaskOrdenoService.cancelOrdeno(e.getOrdeno(), customerCode,user.jobuuid);
			json.put("status", "1");
			json.put("content", "取消成功");
			out.print(json.toString());
		} catch (Exception e1) {
			
			log.error("取消订单接口异常", e1);
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
		}
	}

	private ShiroUser getShiroUser() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user;
	}
}
